﻿/*==========================================
    *   程序说明: 防止HttpPost重复提交 
    *   作者姓名: xp
    *   创建日期: 2106-05-12
    *   最后修改: 
    *   
    *   注: 
    *   版权所有特友 http://o2o.teshehui.com       
==========================================*/

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace TY.UI.Mvc.Extension.ReSubmit
{
    public class SessionPageTokenView : PageTokenViewBase
    {
        #region PageTokenViewBase

        /// <summary>
        /// Generates the page token.
        /// </summary>
        /// <returns></returns>
        public override string GeneratePageToken()
        {
            if (HttpContext.Current.Session[SessionMyToken] != null)
            {
                return HttpContext.Current.Session[SessionMyToken].ToString();
            }
            var token = GenerateHashToken();
            HttpContext.Current.Session[SessionMyToken] = token;
            return token;
        }

        /// <summary>
        /// Gets the get last page token from Form
        /// </summary>
        public override string GetLastPageToken
        {
            get
            {
                return HttpContext.Current.Request.Params[HiddenTokenName];
            }
        }

        /// <summary>
        /// Gets a value indicating whether [tokens match].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [tokens match]; otherwise, <c>false</c>.
        /// </value>
        public override bool TokensMatch
        {
            get
            {
                var formToken = GetLastPageToken;
                if (formToken == null) return false;
                if (!formToken.Equals(GeneratePageToken())) return false;
                //Refresh token
                HttpContext.Current.Session[SessionMyToken] = GenerateHashToken();
                return true;
            }
        }

        #endregion

        #region Private Help Method
        public static string Encrypt(string plaintext)
        {
            var cl1 = plaintext;
            var pwd = string.Empty;
            var md5 = MD5.Create();
            var s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));
            return s.Aggregate(pwd, (current, t) => current + t.ToString("X"));
        }
        /// <summary>
        /// Generates the hash token.
        /// </summary>
        /// <returns></returns>
        private static string GenerateHashToken()
        {
            return Encrypt(HttpContext.Current.Session.SessionID + DateTime.Now.Ticks);
        }
        #endregion
    }
}
